package com.eagle.scali.commoncenter.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * RestTemplate传递用户上下文
 * @author eagle liu
 */
@Slf4j
public class RestTemplateContextInterceptor implements ClientHttpRequestInterceptor {

	@Override
	public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
			throws IOException {
		log.info("Enter restTemplate interceptor..");
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest httpRequest = attributes.getRequest();
		String token = httpRequest.getHeader("X-Token");
		log.info("The token is {}",token);

		Enumeration<String> headerNames = httpRequest.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String name = headerNames.nextElement();
			String values = httpRequest.getHeader(name);
			request.getHeaders().add(name, values);
		}
		log.info("restTemplate>Exchange the token done");
		// 调用
		return execution.execute(request, body);
	}
}
